extends Camera2D

var player_positoin: Vector2 = Vector2.ZERO
var player_born_position: Vector2 = Vector2.ZERO
@export var shakeNoise: FastNoiseLite

# 采样点移动的方向
var xNoiseVector := Vector2.RIGHT
var yNoiseVector := Vector2.DOWN
 
# 噪声采样点的坐标
var xNoisePosition := Vector2.ZERO
var yNoisePosition := Vector2.ZERO

# 采样点移动的速率
var noiseSampleTravelRate := 500

# 相机最大允许的偏移量
var maxShakeOffset := 6
# 相机抖动百分比的衰减速率
var shakeDecay := 4

'''
每次取最大偏移的一定百分比进行实际偏移,
根据游戏的不同事件进行实际偏移相机。
'''
var currentShakePercentage := 0


func _ready() -> void:
	$CPUParticles2D.emitting = true
	get_player_born_pos()
	global_position = player_born_position
	apply_shake(1)
func get_player_born_pos():
	var player_group = get_tree().get_nodes_in_group("players")
	if (player_group.size() > 0):
		var player: Player = player_group[0]
		player_born_position = player.global_position
	
func _physics_process(delta: float) -> void:
	get_player_position()
	global_position = lerp(player_positoin, global_position, pow(2, -15 * delta)).round()
	# 在噪声图像上移动采样点的x位置和y位置坐标
	xNoisePosition += xNoiseVector * noiseSampleTravelRate * delta
	yNoisePosition += yNoiseVector * noiseSampleTravelRate * delta
	
	# 获得噪声的采样 [-1, 1]
	var xSample = shakeNoise.get_noise_2d(xNoisePosition.x, xNoisePosition.y)
	var ySample = shakeNoise.get_noise_2d(yNoisePosition.x, yNoisePosition.y)
	
	# 根据噪声生成一个相机的偏移量
	var calculateOffset = Vector2(xSample, ySample) * pow(currentShakePercentage, 2) * maxShakeOffset
	offset = calculateOffset
	# 使抖动衰减
	currentShakePercentage = clamp(currentShakePercentage - shakeDecay * delta, 0, 1)
	
func get_player_position():
	var player_group = get_tree().get_nodes_in_group("players")
	if (player_group.size() > 0):
		var player: Player = player_group[0]
		player_positoin = player.global_position

func apply_shake(percentage):
	# 防止百分比超过 1，或低于 0
	currentShakePercentage = clamp(currentShakePercentage + percentage, 0, 1)
